<template>
  <div class="addBrand-container">
    <div class="container">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="菜品名称：" prop="name">
          <el-input v-model="formData.name" placeholder="请填写菜品名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="菜品分类：" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择菜品分类">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品价格：" prop="price">
          <el-input v-model="formData.price" placeholder="请设置菜品价格" />
        </el-form-item>

        <el-form-item label="口味做法配置:">
          <div class="flavor-box">
            <el-button @click="addFlavor">+ 添加口味</el-button>
            <div v-if="formData.flavors.length > 0" class="flavor-list">
              <div v-for="(flavor, index) in formData.flavors" :key="index" class="flavor-item">
                <div class="flavor-name">
                  <SelectInput
                    :value="flavor.name"
                    :available-flavors="availableFlavors"
                    @select="(selectedFlavor) => handleFlavorNameSelect(index, selectedFlavor)"
                  />
                </div>
                <div class="flavor-tags">
                  <el-tag
                    v-for="tag in flavor.value"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="removeFlavorTag(index, tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="flavor.inputVisible"
                    :ref="el => tagInputRefs[index] = el"
                    v-model="flavor.inputValue"
                    size="small"
                    class="tag-input"
                    @keyup.enter="handleTagInputConfirm(index)"
                    @blur="handleTagInputConfirm(index)"
                  />
                  <el-button v-else class="button-new-tag" size="small" @click="showTagInput(index)">
                    + 添加
                  </el-button>
                </div>
                <el-button type="text" class="del-flavor-btn" @click="removeFlavor(index)">删除</el-button>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="菜品图片：" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
             <div class="upload-tip">
                图片大小不超过2M<br/>
                仅能上传 PNG JPEG JPG类型图片<br/>
                建议上传200*200或300*300尺寸的图片
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="菜品描述:">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            maxlength="200"
            placeholder="菜品描述，最长200字"
          />
        </el-form-item>

        <div class="subBox">
          <el-form-item>
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="submitForm(false)" :loading="isSaving">保存</el-button>
            <el-button v-if="!isEdit" type="primary" plain @click="submitForm(true)" :loading="isSaving">保存并继续添加</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import { getCategoryList } from '@/api/category';
import { getDishById, addDish, editDish } from '@/api/dish';
import SelectInput from './components/SelectInput.vue';
import type { IDishAddDTO, IDishFlavor } from '@/types/dish';
import type { ICategory } from '@/types/category';
import { useUserStore } from '@/store/user';
import { Plus } from '@element-plus/icons-vue';

// --- State ---
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();
const isSaving = ref(false);
const categoryList = ref<ICategory[]>([]);
const formData = reactive<any>({
  name: '',
  categoryId: '',
  price: '',
  image: '',
  description: '',
  flavors: [],
  status: 1,
});
const tagInputRefs = ref<any[]>([]);

const allFlavorsData = ref([
  { name: '甜味', value: ['无糖', '少糖', '半糖', '多糖', '全糖'] },
  { name: '温度', value: ['热饮', '常温', '去冰', '少冰', '多冰'] },
  { name: '忌口', value: ['不要葱', '不要蒜', '不要香菜', '不要辣'] },
  { name: '辣度', value: ['不辣', '微辣', '中辣', '重辣'] }
]);

// --- Computed ---
const isEdit = computed(() => !!route.params.id);
const dishId = computed(() => Number(route.params.id));

const availableFlavors = computed(() => {
  const selectedNames = new Set(formData.flavors.map((f: { name: string }) => f.name));
  return allFlavorsData.value.filter(f => !selectedNames.has(f.name));
});

const uploadAction = computed(() => `${import.meta.env.VITE_APP_BASE_API}/common/upload`);
const uploadHeaders = computed(() => ({ 'token': userStore.token }));

// --- Form Validation ---
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择菜品分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入菜品价格', trigger: 'blur' }],
  image: [{ required: true, message: '请上传菜品图片', trigger: 'change' }]
});

// --- API Calls & Data Handling ---
const fetchCategoryList = async () => {
  try {
    const res = await getCategoryList({ type: 1 });
    categoryList.value = res.data;
  } catch (error) {
    console.error("获取菜品分类失败:", error);
  }
};

const fetchDishDetail = async (id: number) => {
  try {
    const res = await getDishById(id);
    // 后端返回的 flavors 的 value 是 JSON 字符串，需要解析
    // 并为每个 flavor 添加交互所需的属性
    res.data.flavors = res.data.flavors.map((obj: any) => ({
      ...obj,
      value: JSON.parse(obj.value),
      inputVisible: false,
      inputValue: ''
    }));
    Object.assign(formData, res.data);
  } catch (error) {
    ElMessage.error('获取菜品详情失败');
    router.back(); // 获取失败则返回上一页
  }
};

// --- Event Handlers for Flavors & Upload ---
const addFlavor = () => { formData.flavors.push({ name: '', value: [], inputVisible: false, inputValue: '' }); };
const removeFlavor = (index: number) => { formData.flavors.splice(index, 1); };
const handleFlavorNameSelect = (index: number, selectedFlavor: { name: string, value: string[] }) => {
  formData.flavors[index].name = selectedFlavor.name;
  formData.flavors[index].value = [...selectedFlavor.value];
};
const removeFlavorTag = (flavorIndex: number, tag: string) => { formData.flavors[flavorIndex].value.splice(formData.flavors[flavorIndex].value.indexOf(tag), 1); };
const showTagInput = (index: number) => {
  formData.flavors[index].inputVisible = true;
  nextTick(() => { tagInputRefs.value[index]?.input?.focus(); });
};
const handleTagInputConfirm = (index: number) => {
  const inputValue = formData.flavors[index].inputValue;
  if (inputValue && !formData.flavors[index].value.includes(inputValue)) {
    formData.flavors[index].value.push(inputValue);
  }
  formData.flavors[index].inputVisible = false;
  formData.flavors[index].inputValue = '';
};
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  if (response.code === 1) {
    formData.image = response.data;
    ElMessage.success('图片上传成功！');
  } else {
    ElMessage.error(response.msg || '图片上传失败');
  }
};
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
    ElMessage.error('图片必须是 JPG 或 PNG 格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// --- Form Submission ---
const submitForm = async (continueAdding: boolean) => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      isSaving.value = true;
      try {
        const dataToSubmit = JSON.parse(JSON.stringify(formData));
        // 提交前，将口味的 value 转回 JSON 字符串
        if (dataToSubmit.flavors) {
            dataToSubmit.flavors = dataToSubmit.flavors.map((obj: any) => ({
                ...obj,
                value: JSON.stringify(obj.value)
            }));
        }

        if (isEdit.value) {
          dataToSubmit.id = dishId.value;
          await editDish(dataToSubmit);
          ElMessage.success('菜品修改成功！');
          router.push('/dish');
        } else {
          await addDish(dataToSubmit);
          ElMessage.success('菜品添加成功！');
          if (continueAdding) {
            formRef.value?.resetFields();
            formData.flavors = [];
            formData.image = '';
          } else {
            router.push('/dish');
          }
        }
      } finally {
        isSaving.value = false;
      }
    }
  });
};

// --- Lifecycle Hook ---
onMounted(() => {
  fetchCategoryList();
  if (isEdit.value) {
    fetchDishDetail(dishId.value);
  }
});
</script>
<style lang="scss" scoped>
@import "@/styles/_variables.scss";

.addBrand-container {
  padding: 20px;
}
.container {
  background-color: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}
.el-form {
  max-width: 800px;
  margin: 0 auto;
}
.el-input {
  width: 300px;
}
.flavor-box {
  width: 100%;
}
.flavor-list {
  margin-top: 10px;
  padding: 15px;
  background: #fafafb;
  border: solid 1px #dfe2e8;
  border-radius: 3px;
}
.flavor-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .flavor-name {
    width: 150px;
    margin-right: 15px;
  }
  .flavor-tags {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 10px;
    .tag-input {
      width: 90px;
    }
  }
  .del-flavor-btn {
    margin-left: 15px;
    color: #f56c6c;
  }
}
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
  .upload-tip {
    font-size: 12px;
    color: #999;
    line-height: 1.6;
  }
}
.subBox {
  padding-top: 30px;
  text-align: center;
  border-top: solid 1px #f3f4f7;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>

<style>
/* 全局样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
